#include <iostream>
#include <unistd.h>
#include <cassert>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;

void handler(int signum)
{
    cout << "管道信号错误" << endl;
}

int main()
{

    signal(SIGPIPE,handler);
    int pipefd[2] = {0};
    int res = pipe(pipefd);
    assert(res == 0);
    int id = fork();
    if(id == 0)
    {
        close(pipefd[0]);
        int count = 0;
        while(true)
        {
            char buffer[1024] = "hello world";
            sprintf(buffer,"hello world %d",count);
            count++;
            write(pipefd[1],buffer,sizeof(buffer));
            cout << "child write" << " child pid :" << getpid() << endl;
            sleep(1);
        }
    }
    close(pipefd[1]);
    for(int i = 0;i < 3;i++)
    {
        char buffer[1024];
        read(pipefd[0],buffer,sizeof(buffer));
        cout << "father read " << " father pid :" << getpid() << " buffer :" << buffer << endl; 
    }
    close(pipefd[0]);
    cout << "father read close" << endl;
    int status = 0;
    waitpid(id,&status,0);
    cout << "child exit status:" << status << endl;


    return 0;
}